<template>
  <div>
    <el-form @submit.native.prevent ref="editForm" :model="formFileds">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item>
            <el-input v-model="input" prefix-icon="el-icon-search" placeholder="查询角色名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="get()"> 查询 </el-button>
            <el-button type="primary" @click="add()"> 增加 </el-button>
            <el-button type="primary" @click="deleteSelection">
              批量删除
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--表格内容-->
    <el-table ref="list" :data="tableData" style="width: 100%; margin-bottom: 15px" border highlight-current-row
      :default-sort="{ prop: 'date', order: 'descending' }" @select-all="handleCheckedAllAndCheckedNone"
      @select="handleCheckedAllAndCheckedNone" @selection-change="handleSelectionChange"
      :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column fixed type="selection"> </el-table-column>
      <el-table-column property="name" label="角色名称"> </el-table-column>
      <el-table-column property="status" label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949"
            @change="statusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间">
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" @click="rowEdit(scope.row)" size="mini">编辑
          </el-button>
          <el-button type="danger" size="mini" @click="rowDel(scope.row.id)">删除
          </el-button>
          <el-button type="success" size="mini" @click="getPower(scope.row.id)">授权</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination :page-sizes="[10, 20, 30, 40, 100]" :page-size="pageSize" :total="total"
      @current-change="currentChange" @size-change="sizeChange" layout="total, sizes, prev, pager, next, jumper"
      style="padding-bottom: 15px">
    </el-pagination>

    <add ref="add" v-if="isShowAddDialog" :isShowAddDialog="isShowAddDialog" @dialogClose="dialogClose" @close="get()">
    </add>
    <Edit ref="edit" v-if="isShowEditDialog" :isShowEditDialog="isShowEditDialog" :record="formFileds"
      @dialogClose="dialogClose" @close="get()"></Edit>
    <el-drawer title="菜单权限分配" ref="drawer" :visible.sync="drawer" direction="rtl" size="30%">
      <el-tree :data="dataTree" ref="tree" show-checkbox :expand-on-click-node="false" node-key="id"
        :check-strictly='fSon'>
        <span class="tree-node" slot-scope="{data}">
          <span>{{ data.nameZh }}</span>
        </span>
      </el-tree>
      <div class="treeButton">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="submit">确定
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import add from "./roleManageAdd.vue";
import Edit from "./roleManageEdit.vue";
import { getRole, deleteRole, deleteBatchRole, updateRole, authorization, goPower } from "@/api/systemManage/role";
import { getAll } from "@/api/systemManage/menuManage";
export default {
  name: "roleManage",
  components: { add, Edit },
  data () {
    return {
      text: "",
      multipleSelection: null,
      formFileds: {},
      tableData: [],
      isShowAddDialog: false,
      isShowEditDialog: false,
      pageSize: 10,
      pageNum: 1,
      total: 0,
      input: "",
      drawer: false,
      roleId: '',
      dataTree: [],
      fSon: false,
    };
  },
  methods: {
    // 当前选中仅一行时操作-（当前表格行高亮）
    handleCheckedAllAndCheckedNone (selection) {
      1 != selection.length && this.$refs.list.setCurrentRow();
    },
    // 查询框的值
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    // 选中当前行-当前行的复选框被勾选
    setCurRowChecked (row) {
      this.$refs.list.clearSelection();
      this.$refs.list.toggleRowSelection(row);
    },
    //当前选中行，打开编辑弹窗
    rowEdit (row) {
      this.formFileds = row;
      this.isShowEditDialog = true;
    },
    //对话框关闭
    dialogClose () {
      this.isShowAddDialog = false;
      this.isShowEditDialog = false;
      this.drawer = false
      this.get();
    },
    //打开添加弹窗
    add () {
      this.isShowAddDialog = true;
    },
    //删除按钮
    rowDel (id) {
      // 让当前删除按钮失焦
      // event.target.blur();

      this.$confirm("您确定要删除该角色吗？", "删除", {
        comfirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        deleteRole("id=" + id).then((res) => {
          if (res) {
            this.$message.success("删除成功！");
            this.get();
          }
        });
      });
    },
    // 批量删除
    deleteSelection () {
      if (!this.multipleSelection) {
        this.$message.error("请至少选择一条数据进行删除！");
        return;
      } else {
        this.$confirm("数据将会永久删除，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }).then(() => {
          //生命空数组，这里的数组是后端需要的数据
          let array = [];
          //遍历勾选数据取自己需要的id等 这里是和后端需要的参数对应
          for (let i = 0; i < this.multipleSelection.length; i++) {
            let obj = this.multipleSelection[i].id;
            array.push(obj); //把取出来的对象push到数组里
          }
          let obj = { id: array };
          deleteBatchRole(obj).then((res) => {
            //接口
            this.get(); //删除完成后初始化查询列表
          });
        });
      }
    },
    // 查询角色
    get () {
      var par;
      if (this.input) {
        par = {
          input: this.input,
          pageSize: 10,
          pageNum: 1,
        };
        this.pageSize = 10;
        this.pageNum = 1;
      } else {
        par = {
          input: this.input,
          pageSize: this.pageSize,
          pageNum: this.pageNum,
        };
      }
      getRole(par).then((res) => {
        if (res) {
          this.tableData = res.data.list;
          this.total = res.data.total;
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].status == 0) {
              this.tableData[i].status = true;
            } else {
              this.tableData[i].status = false;
            }
          }
          for (let i = 0; i < this.tableData.length; i++) {
            let newdate = this.tableData[i].createTime;
            this.tableData[i].createTime = newdate.substring(0, 10);
          }
        }
      });
      getAll().then((res) => {
        this.dataTree = res.data
      })
    },
    // 显示当前页
    currentChange (e) {
      this.pageNum = e;
      this.get();
    },
    // 页面显示多少行
    sizeChange (e) {
      this.pageSize = e;
      this.get();
    },
    // 状态按钮修改
    statusChange (row) {
      let obj = Object.assign({}, row);
      if (obj.status == true) {
        obj.status = 0;
      } else {
        obj.status = 1;
      }
      this.$delete(obj, "createTime");
      // let newdate = new Date();
      updateRole(obj).then((res) => {
        this.get();
      });
    },
    getPower (id) {
      this.roleId = id
      this.drawer = true
      goPower('id=' + id).then((res) => {
        if (res.data.length > 0) {
          this.fSon = true
        } else {
          this.fSon = false
        }
        setTimeout(() => {
          this.$refs.tree.setCheckedKeys(res.data);
        }, 0);
        
      })
    },
    submit () {
      let menu = this.$refs.tree.getCheckedNodes(false, true)
      var menuId = []
      for (let i = 0; i < menu.length; i++) {
        menuId.push(menu[i].id)
      }
      let obj = { roleId: this.roleId, menuId: menuId }
      authorization(obj).then((res) => {
        this.$message.success('授权成功！')
        this.get()
        this.drawer = false
      })
    }
  },
  mounted () {
    this.get();
  },
};
</script>

<style scoped lang="less">
.el-form {
  padding: 0 10px;
}

.el-date-editor {
  width: 100% !important;
}

.el-tree {
  padding-left: 10px;
}

/deep/ .el-drawer__header {
  background-color: #2EB3FF;
  align-items: center;
  color: #fff;
  height: 60px;
  margin-bottom: 15px;
  font-weight: bold;

}

.treeButton {
  position: absolute;
  // top: 100%;
  bottom: 25px;
  right: 25px;
}
</style>
